package com.imgo.max.temporary.service;


import com.imgo.max.artist.dto.RankDto;
import com.imgo.max.artist.redis.RedisRanklistDao;
import com.imgo.max.artist.service.FansService;
import com.imgo.max.common.dto.QueryVO;
import com.imgo.max.common.dto.ResultCodeEnum;
import com.imgo.max.common.dto.ResultDO;
import com.imgo.max.mms.dto.VodMediaFileDto;
import com.imgo.max.mms.dto.VodPlayRequest;
import com.imgo.max.mms.service.VodMediaInfoService;
import com.imgo.max.temporary.dto.VigourBoysDto;
import com.imgo.max.temporary.dto.VigourBoysList;
import com.imgo.max.temporary.dto.VigourBoysVideoDto;
import com.imgo.max.temporary.dto.VigourBoysVideoListDto;
import com.imgo.max.timeline.dto.Dynamic;
import com.imgo.max.timeline.service.DynamicAPIService;
import com.imgo.max.user.dto.ArtistUser;
import com.imgo.max.user.dto.Register;
import com.imgo.max.user.dto.User;
import com.imgo.max.user.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by loumingshan on 16/5/15.
 */
@Service("vigourBoysService")
public class VigourBoysServiceImpl implements VigourBoysService {

    private static final Logger log = LoggerFactory.getLogger(VigourBoysServiceImpl.class);


    @Resource
    UserService userService;

    @Resource
    FansService fansService;

    @Resource
    RedisRanklistDao redisRanklistDao;

    @Resource
    DynamicAPIService dynamicAPIService;

    @Resource
    VodMediaInfoService vodMediaInfoService;

    /**
     * 查询参加某个活动的总人气某个排行数据
     *
     * @param nextId     排名开始id
     * @param count      要查询开始id后的多少个数据
     * @param columnid   活动id
     * @param simpleFlag 简单flag,true:只获取uids,false还会获取其他信息
     * @return
     */
    @Override
    public ResultDO<VigourBoysList> topUserList(int nextId, int count, Integer columnid, boolean simpleFlag) {
        ResultDO<VigourBoysList> result = new ResultDO<VigourBoysList>();
        VigourBoysList vigourBoysList = new VigourBoysList();
        List<VigourBoysDto> list = new ArrayList<VigourBoysDto>();

        try {
            //调用接口获取人气美少年的所有用户数据
            List<ArtistUser> artists = userService.queryAristListByColumnid(columnid, null);
            //如果返回数据不为空,则将uids取出来
            if (artists != null) {
                List<String> uids = new ArrayList<>();
                for (ArtistUser au : artists) {
                    uids.add(au.getUid());
                }
                list = getListResultDO(nextId, count, uids, simpleFlag);
                vigourBoysList.setCount(list.size());
                vigourBoysList.setTotal(artists.size());
                vigourBoysList.setUids(list);
                if (artists.size() < 1000) {
                    vigourBoysList.setNextId(artists.size());

                } else {
                    vigourBoysList.setNextId(nextId + 1000);

                }

            } else {
                vigourBoysList.setCount(0);
                vigourBoysList.setTotal(0);
                vigourBoysList.setUids(null);
                vigourBoysList.setNextId(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(ResultCodeEnum.VIGOUR_BOYS_LIST_GET_USER_LIST_ERROR.getResultCode());
            result.setErrorMessage(ResultCodeEnum.VIGOUR_BOYS_LIST_GET_USER_LIST_ERROR.getMessage());
            result.setErrorMessage(e.getMessage());
        }
        result.setModule(vigourBoysList);
        return result;
    }

    @Override
    public ResultDO<VigourBoysDto> userInfo(String id, Integer columnid) {

        ResultDO<VigourBoysDto> result = new ResultDO<VigourBoysDto>();
        VigourBoysDto vigourBoysDto = new VigourBoysDto();
        try {

            User user = new User();
            user.setUid(id);
            ResultDO<User> userResultDO = userService.getUserInfo(user);
            if (userResultDO.isSuccess() && userResultDO.getModule() != null) {
                User u = userResultDO.getModule();

                vigourBoysDto.setUsername(u.getNickName() == null ? "" : u.getNickName());
                vigourBoysDto.setCity(u.getCity() == null ? "" : u.getCity());
                vigourBoysDto.setCountry(u.getCountry() == null ? "" : u.getCountry());
                vigourBoysDto.setHeadimgurl(u.getPhoto() == null ? "" : u.getPhoto());
                vigourBoysDto.setMobile(u.getPhoneNum() == null ? "" : u.getPhoneNum());
                vigourBoysDto.setProvince(u.getProvince() == null ? "" : u.getProvince());
                vigourBoysDto.setSex(u.getSex() == null ? 1 : u.getSex());

            }
            ResultDO<Integer> res =
                    fansService.getFansNum(id);
            if (result.isSuccess() && res.getModule() != null) {

                vigourBoysDto.setFanscount(res.getModule());
            } else {
                vigourBoysDto.setFanscount(0);

            }

            Register register = new Register();
            register.setUid(id);
            register.setColumnId(columnid);
            register.setStatus(0);
            ResultDO<Register> resultDO = userService.queryEnterInfoById(register);
            if (resultDO.isSuccess() && resultDO.getModule() != null && resultDO.getModule().getVideo() != null) {
                vigourBoysDto.setVideo(getVideoUrl(resultDO.getModule().getVideo()));

            } else {
                vigourBoysDto.setVideo("");

            }


            vigourBoysDto.setUserid(id);
            RankDto rdo = redisRanklistDao.getUserRankInfo(id);
            if (rdo != null) {
                vigourBoysDto.setCount(rdo.getPopularityInc());
            } else {
                vigourBoysDto.setCount(0);

            }

            QueryVO queryVO = new QueryVO();
            queryVO.setUid(id);
            queryVO.setStatus("1");
            queryVO.setType("2");
            queryVO.setPage(1);
            queryVO.setPageSize(9999);
            //获取动态的视频
            ResultDO<List<Dynamic>> dyResult = dynamicAPIService.queryDynamicList(queryVO, 2);

            //如果没数据说明只有报名的一条
            if (dyResult.getModule() != null) {

                //log.error("dynamicAPIService size"+dyResult.getModule().size());
                //判断报名的视频有没有在动态里面
                boolean flag = false;
                for (Dynamic dy : dyResult.getModule()) {
                    if (vigourBoysDto.getVideo().equals(dy.getVideo())) {
                        flag = true;
                        break;
                    }
                }
                //如果在里面则视频数量等于动态的视频数量
                if (flag) {
                    vigourBoysDto.setVideocount(dyResult.getModule().size());

                }
                //如果不在,则视频数量等于动态视频+1
                else {
                    vigourBoysDto.setVideocount(1 + dyResult.getModule().size());
                }

            } else {
                vigourBoysDto.setVideocount(1);
                //log.error("dynamicAPIService size    null");


            }


            vigourBoysDto.setHome("http://share.max.mgtv.com/artist/space/?auid=" + id);


        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(ResultCodeEnum.VIGOUR_BOYS_LIST_DETAIL_ERROR.getResultCode());
            result.setErrorMessage(ResultCodeEnum.VIGOUR_BOYS_LIST_DETAIL_ERROR.getMessage());
            result.setErrorMessage(e.getMessage());
        }
        result.setModule(vigourBoysDto);
        return result;
    }

    @Override
    public ResultDO<VigourBoysVideoListDto> videoList(String id, int offset) {
        ResultDO<VigourBoysVideoListDto> result = new ResultDO<VigourBoysVideoListDto>();
        VigourBoysVideoListDto vigourBoysVideoListDto = new VigourBoysVideoListDto();
        List<VigourBoysVideoDto> list = new ArrayList<>();
        try {
            QueryVO queryVO = new QueryVO();
            queryVO.setUid(id);
            queryVO.setStatus("1");
            queryVO.setType("2");
            queryVO.setPage(0);
            queryVO.setPageSize(9999);
            //获取动态的视频
            ResultDO<List<Dynamic>> dyResult = dynamicAPIService.queryDynamicList(queryVO, 2);
            Register register = new Register();
            register.setUid(id);
            register.setColumnId(300001);
            register.setStatus(0);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            ResultDO<Register> resultDO = userService.queryEnterInfoById(register);
            if (resultDO.isSuccess() && resultDO.getModule() != null && resultDO.getModule().getVideo() != null) {
                VigourBoysVideoDto vigourBoysVideoDto = new VigourBoysVideoDto();
                vigourBoysVideoDto.setMediaurl(getVideoUrl(resultDO.getModule().getVideo()));
                vigourBoysVideoDto.setName(resultDO.getModule().getContent() == null ? "" : resultDO.getModule().getContent());
                vigourBoysVideoDto.setUpdate_time(resultDO.getModule().getCreateTime());
                list.add(vigourBoysVideoDto);
                if (dyResult != null && dyResult.getModule() != null) {

                    for (Dynamic dynamic : dyResult.getModule()) {

                        if (!dynamic.getVideo().equals(resultDO.getModule().getVideo())) {
                            vigourBoysVideoDto = new VigourBoysVideoDto();
                            vigourBoysVideoDto.setMediaurl(getVideoUrl(dynamic.getVideo()));
                            vigourBoysVideoDto.setName(dynamic.getContent());
                            if (dynamic.getOriginDate() != null) {
                                Date d1 = df.parse(dynamic.getOriginDate());

                                vigourBoysVideoDto.setUpdate_time(d1);
                            }
                            list.add(vigourBoysVideoDto);
                        }

                    }
                }


            } else {
                if (dyResult != null && dyResult.getModule() != null) {
                    VigourBoysVideoDto vigourBoysVideoDto = null;
                    for (Dynamic dynamic : dyResult.getModule()) {

                        vigourBoysVideoDto = new VigourBoysVideoDto();
                        vigourBoysVideoDto.setName(dynamic.getContent());
                        if (dynamic.getOriginDate() != null) {
                            Date d1 = df.parse(dynamic.getOriginDate());

                            vigourBoysVideoDto.setUpdate_time(d1);
                        }
                        vigourBoysVideoDto.setMediaurl(getVideoUrl(dynamic.getVideo()));
                        list.add(vigourBoysVideoDto);

                    }

                }


            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(ResultCodeEnum.VIGOUR_BOYS_LIST_VIDEO_ERROR.getResultCode());
            result.setErrorMessage(ResultCodeEnum.VIGOUR_BOYS_LIST_VIDEO_ERROR.getMessage());
            result.setErrorMessage(e.getMessage());
        }
        vigourBoysVideoListDto.setList(list);
        result.setModule(vigourBoysVideoListDto);
        return result;
    }


    private VigourBoysDto changeResultToDto(RankDto rankDto, int i) {
        VigourBoysDto vigourBoysDto = new VigourBoysDto();
        User user = new User();
        user.setUid(rankDto.getArtistId());
        ResultDO<User> result = userService.getUserInfo(user);
        if (result.isSuccess() && result.getModule() != null) {
            vigourBoysDto.setUsername(result.getModule().getNickName() == null ? "" : result.getModule().getNickName());
            vigourBoysDto.setCity(result.getModule().getCity() == null ? "" : result.getModule().getCity());
            vigourBoysDto.setCountry(result.getModule().getCountry() == null ? "" : result.getModule().getCountry());
            vigourBoysDto.setHeadimgurl(result.getModule().getPhoto() == null ? "" : result.getModule().getPhoto());
            vigourBoysDto.setMobile(result.getModule().getPhoneNum() == null ? "" : result.getModule().getPhoneNum());
            vigourBoysDto.setProvince(result.getModule().getProvince() == null ? "" : result.getModule().getProvince());
            vigourBoysDto.setSex(result.getModule().getSex() == null ? 1 : result.getModule().getSex());


        }
        ResultDO<Integer> res =
                fansService.getFansNum(rankDto.getArtistId());
        if (result.isSuccess()) {

            vigourBoysDto.setFanscount(res.getModule());
        } else {
            vigourBoysDto.setFanscount(0);

        }

        Register register = new Register();
        register.setUid(rankDto.getArtistId());
        register.setColumnId(300001);
        register.setStatus(0);
        ResultDO<Register> resultDO = userService.queryEnterInfoById(register);
        if (resultDO.isSuccess() && resultDO.getModule() != null && resultDO.getModule().getVideo() != null) {
            vigourBoysDto.setVideo(getVideoUrl(resultDO.getModule().getVideo()));

        } else {
            vigourBoysDto.setVideo("");

        }


        vigourBoysDto.setId(i);
        vigourBoysDto.setUserid(rankDto.getArtistId());
        vigourBoysDto.setCount(rankDto.getPopularityInc());
        vigourBoysDto.setHome("http://share.max.mgtv.com/artist/space/?auid=" + rankDto.getArtistId());


        return vigourBoysDto;

    }

    /**
     * 根据uid获取人气值
     * @param uids
     * @return
     */
    @Override
    public ResultDO<List<RankDto>>getPopularity(List<String> uids) {
        ResultDO< List<RankDto>> result = new ResultDO<>();
        List<RankDto> ranklist = new ArrayList<RankDto>();
        //根据id获取人气值就是分值
        try{
        Iterator<RankDto> it = redisRanklistDao.getArtistsRankMap(uids).values().iterator();

        //将返回结果转化成list
        while (it.hasNext()) {
            ranklist.add(it.next());
        }
        if (CollectionUtils.isNotEmpty(ranklist)) {


            //根据人气将uids进行排序
            Collections.sort(ranklist, new Comparator<RankDto>() {
                public int compare(RankDto arg0, RankDto arg1) {
                    return arg1.getPopularityInc().intValue()-arg0.getPopularityInc().intValue();
                }
            });

            result.setModule(ranklist);
        }}
        catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setResultCode(ResultCodeEnum.COMMON_FAIL.getResultCode());
            result.setErrorMessage(ResultCodeEnum.COMMON_FAIL.getMessage());
            result.setErrorMessage(e.getMessage());
        }
        return result;


    }


    /**
     * 根据传入的艺人列表获取从begin开始的top num的数据
     *
     * @param begin      人气排名的开始位置
     * @param num        需要获取的排名数据
     * @param simpleFlag 如果为true则返回的是排名跟uid,如果为false则返回详细的用户信息,专门为top10用的
     * @param uids       根据活动查询出来的uid列表
     * @return
     * @throws Exception
     */
    private List<VigourBoysDto> getListResultDO(int begin, int num, List<String> uids, boolean simpleFlag) throws Exception {
        //返回的数据列表
        List<VigourBoysDto> list = new ArrayList<VigourBoysDto>();


        List<RankDto> ranklist = new ArrayList<RankDto>();

        //根据id获取人气值就是分值
        Iterator<RankDto> it = redisRanklistDao.getArtistsRankMap(uids).values().iterator();

        //将返回结果转化成list
        while (it.hasNext()) {
            ranklist.add(it.next());
        }


        if (CollectionUtils.isNotEmpty(ranklist)) {


            //根据人气将uids进行排序
            Collections.sort(ranklist, new Comparator<RankDto>() {
                public int compare(RankDto arg0, RankDto arg1) {
                    return arg1.getPopularityInc().compareTo(arg0.getPopularityInc());
                }
            });


            //如果返回的人气数据少于num个,择取全部数据
            if (simpleFlag) {
                if (ranklist != null && ranklist.size() <= num + begin) {

                    for (int i = begin; i < ranklist.size(); i++) {
                        VigourBoysDto vigourBoysDto = new VigourBoysDto();
                        vigourBoysDto.setId(i);
                        vigourBoysDto.setUserid(ranklist.get(i).getArtistId());
                        list.add(vigourBoysDto);
                    }
                }
                //如果人气数据大于10个择取前面num个s
                if (ranklist != null && ranklist.size() > num + begin) {

                    for (int i = begin; i < num + begin; i++) {

                        VigourBoysDto vigourBoysDto = new VigourBoysDto();
                        vigourBoysDto.setId(i);
                        vigourBoysDto.setUserid(ranklist.get(i).getArtistId());
                        list.add(vigourBoysDto);
                    }
                }
            } else {


                if (ranklist != null && ranklist.size() <= num + begin) {

                    for (int i = begin; i < ranklist.size(); i++) {

                        list.add(changeResultToDto(ranklist.get(i), i));
                    }
                }
                //如果人气数据大于10个择取前面num个
                if (ranklist != null && ranklist.size() > num + begin) {

                    for (int i = begin; i < num + begin; i++) {

                        list.add(changeResultToDto(ranklist.get(i), i));

                    }
                }


            }
        }


        return list;
    }

    private String getVideoUrl(String key) {


        VodPlayRequest play = new VodPlayRequest();
        play.setFileKey(key);
        play.setFormat("MP4");
        VodMediaFileDto file = vodMediaInfoService.queryVodSourceBak(play)
                .getModule();
        String url = "";
        if (file != null && file.getVideoUrl() != null) {
            url = file.getVideoUrl();
        }
        return url;

    }


}
